package com.example.show_auto.data

import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
import com.example.show_auto.ui.pages.UltimateSkillsState
import com.example.show_auto.ui.pages.RecipeLimitsState
import com.example.show_auto.ui.pages.RecipePricesState

/**
 * 修炼数据持久化存储管理器
 * 支持多用户数据隔离
 */
class UltimateDataStorage(context: Context) {
    
    private val sharedPreferences: SharedPreferences = 
        context.getSharedPreferences("ultimate_data", Context.MODE_PRIVATE)
    private val gson = Gson()
    private val contextRef = context // 保存context引用，用于动态创建MultiUserDataManager
    
    companion object {
        private const val KEY_ULTIMATE_SKILLS = "ultimate_skills"
        private const val KEY_RECIPE_LIMITS = "recipe_limits"
        private const val KEY_RECIPE_PRICES = "recipe_prices"
        private const val KEY_HAS_DATA = "has_data"
    }
    
    /**
     * 获取当前用户ID
     */
    private fun getCurrentUserId(): String? {
        val multiUserDataManager = MultiUserDataManager(contextRef)
        return multiUserDataManager.getCurrentUserId()
    }
    
    /**
     * 根据用户ID生成带前缀的key
     */
    private fun getKeyWithUserId(baseKey: String): String {
        val userId = getCurrentUserId()
        return if (userId != null) {
            "${userId}_$baseKey"
        } else {
            baseKey // 兼容旧版本，没有用户ID时使用原key
        }
    }
    
    /**
     * 保存修炼数据
     */
    fun saveUltimateData(
        ultimateSkills: UltimateSkillsState,
        recipeLimits: RecipeLimitsState,
        recipePrices: RecipePricesState
    ) {
        val currentUserId = getCurrentUserId()
        if (currentUserId == null) return // 如果没有当前用户，不保存数据
        
        sharedPreferences.edit().apply {
            putString(getKeyWithUserId(KEY_ULTIMATE_SKILLS), gson.toJson(ultimateSkills))
            putString(getKeyWithUserId(KEY_RECIPE_LIMITS), gson.toJson(recipeLimits))
            putString(getKeyWithUserId(KEY_RECIPE_PRICES), gson.toJson(recipePrices))
            putBoolean(getKeyWithUserId(KEY_HAS_DATA), true)
            apply()
        }
    }
    
    /**
     * 加载修炼数据
     */
    fun loadUltimateData(): Triple<UltimateSkillsState, RecipeLimitsState, RecipePricesState>? {
        if (!hasData()) return null
        
        return try {
            val ultimateSkillsJson = sharedPreferences.getString(getKeyWithUserId(KEY_ULTIMATE_SKILLS), null)
            val recipeLimitsJson = sharedPreferences.getString(getKeyWithUserId(KEY_RECIPE_LIMITS), null)
            val recipePricesJson = sharedPreferences.getString(getKeyWithUserId(KEY_RECIPE_PRICES), null)
            
            if (ultimateSkillsJson != null && recipeLimitsJson != null && recipePricesJson != null) {
                val ultimateSkills = gson.fromJson(ultimateSkillsJson, UltimateSkillsState::class.java)
                val recipeLimits = gson.fromJson(recipeLimitsJson, RecipeLimitsState::class.java)
                val recipePrices = gson.fromJson(recipePricesJson, RecipePricesState::class.java)
                
                Triple(ultimateSkills, recipeLimits, recipePrices)
            } else {
                null
            }
        } catch (e: Exception) {
            null
        }
    }
    
    /**
     * 检查是否有保存的数据
     */
    fun hasData(): Boolean {
        return sharedPreferences.getBoolean(getKeyWithUserId(KEY_HAS_DATA), false)
    }
    
    /**
     * 清除当前用户的修炼数据
     */
    fun clearData() {
        val currentUserId = getCurrentUserId()
        if (currentUserId == null) return // 如果没有当前用户，不执行清除操作
        
        sharedPreferences.edit().apply {
            remove(getKeyWithUserId(KEY_ULTIMATE_SKILLS))
            remove(getKeyWithUserId(KEY_RECIPE_LIMITS))
            remove(getKeyWithUserId(KEY_RECIPE_PRICES))
            remove(getKeyWithUserId(KEY_HAS_DATA))
            apply()
        }
    }
}